#include <iostream>

using std::cout;
using std::endl;

//单例模式的自动释放第一种形式：友元类
class Singleton
{
    friend class AutoRelease;
public:
    static Singleton *getInstance()
    {
        if(nullptr == _pInstance)
        {
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
#if 0
    static void destroy()
    {
        if(_pInstance)
        {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }
#endif

private:
    Singleton()
    {
        cout <<"Singleton()" << endl;
    }

    ~Singleton()
    {
        cout <<"~Singleton()" << endl;
    }

private:
    static Singleton *_pInstance;
};

Singleton *Singleton::_pInstance = nullptr;

class AutoRelease
{
public:
    AutoRelease()
    {
        cout << "AutoRelease()" << endl;
    }

    ~AutoRelease()
    {
        cout << "~AutoRelease()" << endl;
        if(Singleton::_pInstance)
        {
            delete Singleton::_pInstance;
            Singleton::_pInstance = nullptr;
        }
    }
};
void test()
{
    Singleton::getInstance();
    AutoRelease ar;//创建栈对象
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

